package com.zj.core.activity

import android.graphics.Bitmap
import android.view.View
import android.widget.LinearLayout
import com.fileutils.ImageFileUtil
import com.utils.DateUtils
import com.zj.core.R
import com.zj.core.base.TitleBarActivity
import com.zj.core.tools.Constant.Companion.PICTURE_RES_KEY
import com.utils.DateUtils.DATE_FORMAT_14
import com.dialogutils.ToastUtil
import com.zj.core.bean.EventBusMessage
import com.zj.core.bean.EventBusMessage.Companion.PHOTO_CUT_TAG
import com.zj.core.ui.PictureActivityUi
import com.zj.core.tools.Constant
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.setContentView


class PictureActivity: TitleBarActivity(),View.OnClickListener{
    private var pictureBean:ImageFileUtil.CustomClass?=null
    private var mBitmap:Bitmap?=null
    private var croppedImage:Bitmap?=null
    lateinit var view: PictureActivityUi

    override fun onCreate(groupView: LinearLayout): View? {
        view= PictureActivityUi(groupView)
        return view.setContentView(this)
    }

    override fun initView() {
        setTitleText("裁剪")
        pictureBean=intent.getSerializableExtra(PICTURE_RES_KEY) as ImageFileUtil.CustomClass?

        mBitmap = ImageFileUtil.analyzePic(this,pictureBean, pictureBean?.isTakePhoto!!)
        with(view){
            if (mBitmap != null){
                this.crop_image_view.setImageBitmap(mBitmap)
            }
            this.btn_rotate.setOnClickListener(this@PictureActivity)
            this.btn_ok.setOnClickListener(this@PictureActivity)
        }
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when(v?.id){
            R.id.btn_rotate->{                          //旋转
                view.crop_image_view.rotateImage(90)
            }

            R.id.btn_ok->{                              //确定
                croppedImage = view.crop_image_view.croppedImage
                croppedImage?.let {
                    ImageFileUtil.saveImage(
                        it,
                        Constant.fileSavePath(this, DateUtils.getNowDateFormat(DATE_FORMAT_14))
                    )
                    EventBus.getDefault().post(EventBusMessage(PHOTO_CUT_TAG))
                    CameraActivity.CameraActivity?.finish()
                    finish()
                }?:let {
                    ToastUtil.showShort(this, "裁剪失败")
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if(pictureBean!=null){
            pictureBean=null
        }

        if(mBitmap!=null){
            mBitmap=null
        }

        if(croppedImage!=null){
            croppedImage=null
        }
    }
}